package dao;

import tool.Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MessageDao {
    private final Util util = new Util();
    private Connection connection = null;

    public void addMessage(String fromName, String toName, String message) {
        connection = util.getConnection();
        String sql = "insert into message(from_name, to_name, message) VALUES (?,?,?)";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, fromName);
            preparedStatement.setString(2, toName);
            preparedStatement.setString(3, message);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public String[] getMessages(String fromName, String toName) {
        connection = util.getConnection();
        List<String> messageList = new ArrayList<>();
        String sql = "select * from message where ((from_name =? and to_name =?) or (from_name =? and to_name =?))and status=0";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, fromName);
            preparedStatement.setString(2, toName);
            preparedStatement.setString(3, toName);
            preparedStatement.setString(4, fromName);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                String string1 = resultSet.getString("message");
                String string2 = resultSet.getString("from_name");
                String string3 = resultSet.getString("to_name");
                String string = string2 + ":" + string3 + ":" + string1;
                messageList.add(string);
            }
            String[] usersArray = new String[messageList.size()];
            usersArray = messageList.toArray(usersArray);
            return usersArray;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}